package org.grow.linyi.controller;

import org.grow.linyi.dao.JpaMainBlog;
import org.grow.linyi.entity.MainBlog;
import org.grow.linyi.service.BlogService;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Controller
public class SimpleBlog {
    @Autowired
    private JpaMainBlog jpaMainBlog;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private BlogService blogService;
    @GetMapping("/")
    public ModelAndView index() {
        String username = "张三";
        ModelAndView general = new ModelAndView("general");
        List<MainBlog> all = jpaMainBlog.findAll();
        System.out.println(all);
        general.addObject("blogs", all);
        general.addObject("username", username);

        return general;
    }
    @GetMapping("/another")
    public ModelAndView welcome(){
        String username = "张三";
        ModelAndView general = new ModelAndView("general");
        String sql = "select m.id, m.createTime ,m.shortContent ,m.title,m.browseNum,m.praiseNum ,m.author from MainBlog m\n" +
                "order by m.createTime desc\n" +
                "limit 10";
        List resultList =entityManager.createNativeQuery(sql)
                .unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                .getResultList();
        System.out.println(resultList);
        general.addObject("blogs", resultList);
        general.addObject("username", username);

        return general;
    }
    @GetMapping("/detail")
    public ModelAndView detail(@RequestParam("id") Long id){
        MainBlog blog = blogService.browser(id);
        ModelAndView detail = new ModelAndView("detail");
        detail.addObject("blog",blog);
        return detail;
    }
    @GetMapping("/newBlogPage")
    public String newBlogPage(){
        return "newBlog";
    }

    @PostMapping("/saveBlog")
    public void save(@RequestParam String title,
                     @RequestParam String content,
                     HttpServletRequest request,
                     HttpServletResponse response) throws IOException {
        try{
            blogService.saveBlog(title, content);

        }catch (Exception e){
            response.sendRedirect("/error?e="+e.getLocalizedMessage());

        }
        response.sendRedirect("/");

    }
    @GetMapping("/error")
    public ModelAndView error(HttpServletRequest request){
        Object e = request.getParameter("e");
        ModelAndView error = new ModelAndView("error");
        error.addObject("e",e);
        return error;
    }

    @GetMapping("/test4")
    public String test4(){
        String createDate = LocalDateTime.now().minusDays(6).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String sql = String.format("select b.id,b.author,b.browseNum,b.title,b.shortContent from MainBlog b\n" +
                "where b.createTime > date('%s')",createDate);
        Query nativeQuery = entityManager.createNativeQuery(sql);
        List resultList = nativeQuery.unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                .getResultList();
        resultList.forEach((o)->{
            System.out.println(o.getClass());
            try{
                System.out.println(Arrays.toString((Object[])o));
            }catch (Exception e){
                System.out.println(o);
            }
        });
        return "newBlog";
    }
}
